package com.ultrasoft.farmasoft.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.ultrasoft.farmasoft.domain.Activesubstance;
import com.ultrasoft.farmasoft.domain.Composition;
import com.ultrasoft.farmasoft.domain.Country;
import com.ultrasoft.farmasoft.domain.Item;
import com.ultrasoft.farmasoft.domain.Locality;
import com.ultrasoft.farmasoft.domain.Package;
import com.ultrasoft.farmasoft.domain.Pharmacyproduct;
import com.ultrasoft.farmasoft.domain.Pharmacystock;
import com.ultrasoft.farmasoft.domain.Product;
import com.ultrasoft.farmasoft.domain.Productattribute;
import com.ultrasoft.farmasoft.domain.Productattributes;
import com.ultrasoft.farmasoft.domain.Provider;
import com.ultrasoft.farmasoft.domain.Providerpharmacy;
import com.ultrasoft.farmasoft.domain.Stock;
import com.ultrasoft.farmasoft.domain.Typecomposition;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.domain.Userprovider;
import com.ultrasoft.farmasoft.domain.UserproviderPK;
import com.ultrasoft.farmasoft.service.BuyProductsTransactionService;
import com.ultrasoft.farmasoft.service.ConfigServiceProducts;
import com.ultrasoft.farmasoft.service.HumanResourcesService;
import com.ultrasoft.farmasoft.service.ProviderService;
import com.ultrasoft.farmasoft.service.StockService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;


@Controller
@SessionAttributes({"s_UserPharmacy"}) 
@RequestMapping(value="/Transaction")
public class TransactionBuyProductsController {
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	
	public String providerId_	= "_providerId";
	public String productId_	= "_productId";

	
	private final ProviderService providerService;
	private final StockService stockService;
	private final ConfigServiceProducts configServiceProducts;
	private final BuyProductsTransactionService buyProductsTransactionService;
	
	@Autowired
    public TransactionBuyProductsController(BuyProductsTransactionService buyProductsTransactionService,ConfigServiceProducts configServiceProducts,StockService stockService,ProviderService providerService) {
        this.providerService				= providerService;
        this.stockService 					= stockService;
        this.configServiceProducts 			= configServiceProducts;
        this.buyProductsTransactionService	= buyProductsTransactionService;
    }
	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}

	private String redirectTransactionBuyProducts(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/buyProducts?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}
	
	@RequestMapping(value="/buyProducts", method=RequestMethod.GET)
	public String handleRequestTransactionBuyProducts(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){			
			//model.addAttribute("listProductActive",configServiceProducts.getListProductByPharmacyId(s_pharmacyId,true));//getListProductTemp());//configServiceProducts.getListProductByPharmacyId(s_pharmacyId,true));
			model.addAttribute("listProvider",providerService.getListProvider(s_pharmacyId,true));
			model.addAttribute("listVisitor",providerService.getListUserProviderByRolProviderIdByActive(2,true));		// value 2 : all Visitors
			//return UtilCommon.fOperation_BuyProducts+"purchaseProducts";
			return UtilCommon.fTransaction_BuyProducts+"purchaseProducts";
		}else
			return redirectTransactionBuyProducts(request);
	}		
	@RequestMapping(value = "/loadTableTemp", method = RequestMethod.GET)
   	public @ResponseBody Map<String, Object> handleRequestLoadTableTemp(HttpServletRequest request){			
		Map<String, Object> map = new HashMap<String,Object>();		
		//System.out.println(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId")));
		map.put("listPharmacyStock",getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId"))));
		map.put("listProductActive",getListProductTemp(configServiceProducts.getListProductByPharmacyIdByProviderId(s_pharmacyId, UtilConverter.converterStringToInteger(request,"providerId"), true)));
		return map;
    }	
	@RequestMapping(value = "/loadTableTempByName", method = RequestMethod.GET)
   	public @ResponseBody Map<String, Object> handleRequestLoadTableTempByName(HttpServletRequest request){			
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("listPharmacyStock",getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId"))));
		map.put("listProductActive",getListProductTemp(configServiceProducts.getListProductByPharmacyIdByproviderIdByActiveByName(s_pharmacyId, UtilConverter.converterStringToInteger(request,"providerId"), true,UtilConverter.converterStringToString(request,"name"))));
		return map;
    }
	@RequestMapping(value = "/loadTableTempByCode", method = RequestMethod.GET)
   	public @ResponseBody Map<String, Object> handleRequestLoadTableTempByCode(HttpServletRequest request){			
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("listPharmacyStock",getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId"))));
		map.put("listProductActive",getListProductTemp(configServiceProducts.getListProductByPharmacyIdByproviderIdByActiveByCode(s_pharmacyId, UtilConverter.converterStringToInteger(request,"providerId"), true,UtilConverter.converterStringToString(request,"code"))));
		return map;
    }
	@RequestMapping(value = "/loadTableTempByCodeBar", method = RequestMethod.GET)
   	public @ResponseBody Map<String, Object> handleRequestLoadTableTempByCodeBar(HttpServletRequest request){			
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("listPharmacyStock",getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId"))));
		map.put("listProductActive",getListProductTemp(configServiceProducts.getListProductByPharmacyIdByproviderIdByActiveByCodeBar(s_pharmacyId, UtilConverter.converterStringToInteger(request,"providerId"), true,UtilConverter.converterStringToString(request,"codeBar"))));
		return map;
    }
	
	
	@RequestMapping(value = "/loadTableTempBySelect", method = RequestMethod.GET)
   	public @ResponseBody Map<String, Object> handleRequestLoadTableTempBySelect(HttpServletRequest request){			
		Map<String, Object> map = new HashMap<String,Object>();
		List<Product> listProduct = getListProductTemp(configServiceProducts.getListProductByPharmacyId(s_pharmacyId,true));
		List<Pharmacystock> listPS = getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyId(s_pharmacyId));
		map.put("listPharmacyStock",listPS);
		map.put("listProductActive",listProduct);
		/*
		for (Pharmacystock pharmacystock : listPS) {
			pharmacystock.getStock().getItemCollection();
		}
		*/
		//List<Pharmacystock> listPS2 = new ArrayList<Pharmacystock>();
		//map.put("listPharmacyStock",getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId"))));
		//map.put("listProductActive",getListProductTemp(configServiceProducts.getListProductByPharmacyIdByproviderIdByActiveByCodeBar(s_pharmacyId, UtilConverter.converterStringToInteger(request,"providerId"), true,UtilConverter.converterStringToString(request,"codeBar"))));
		return map;
    }
	
	@RequestMapping(value="/formNewPharmacyProduct", method=RequestMethod.GET)
	public String handleRequestFormNewPharmacyProduct(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	
		    Pharmacyproduct pp = buyProductsTransactionService.searchPharmacyProductByPharmacyIdByProviderIdByProductId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"_providerId"),UtilConverter.converterStringToInteger(request,"_productId"));
		    if(pp == null)
		    	pp = new Pharmacyproduct();		
		    else{
		    	List<Package> listPackage = buyProductsTransactionService.getListPackageByPharmacyProductByActive(pp, true);
		    	pp.setPackageCollection(listPackage);
		    	if(!listPackage.isEmpty())
		    		model.addAttribute("packageTemp",listPackage.get(listPackage.size()-1));
		    }
			model.addAttribute("_productId",request.getParameter(productId_));
			model.addAttribute("_providerId",request.getParameter(providerId_));
			model.addAttribute("listPharmacyStock",getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId_"))));

			model.addAttribute("provider",providerService.searchProviderByProviderId(UtilConverter.converterStringToInteger(request,providerId_)));
			model.addAttribute("pharmacyProduct",pp);
			return UtilCommon.fReferenceAdd+"formPharmacyProduct";
		}else
			return redirectTransactionBuyProducts(request);
	}
	@RequestMapping(value = "/formNewPharmacyProduct", method = RequestMethod.POST)
   	public @ResponseBody Map<String, Object> onSubmitFormNewPharmacyProduct(@Valid Pharmacyproduct pharmacyProduct,BindingResult result,Model model,HttpServletRequest request){			
		String msg="";
	    pharmacyProduct.setActive(true);    
	    Pharmacyproduct pharmacyProductTemp = buyProductsTransactionService.searchPharmacyProductByPharmacyIdByProviderIdByProductId(pharmacyProduct.getPharmacyproductPK().getPharmacyId(),pharmacyProduct.getPharmacyproductPK().getProviderId(),pharmacyProduct.getPharmacyproductPK().getProductId());
	    int purchaseUnit = UtilConverter.converterStringToInteger(request,"_purchaseUnit");
	    int i = 1;
	    if( purchaseUnit == 1){			// 1:package , 0:units
	    	i = UtilConverter.converterStringToInteger(request,"_quantityOfPackage");
	    	pharmacyProduct.setPackage1(true);	
	    	pharmacyProduct.setValueTempCountItem(UtilConverter.converterStringToShort(request,"_unitsByPackage"));
	    	pharmacyProduct.setValueTempCountPackage((short)i);
	    }else{
	    	pharmacyProduct.setPackage1(false);	    	
	    	pharmacyProduct.setValueTempCountItem(UtilConverter.converterStringToShort(request,"_quantityOfUnits"));
	    	pharmacyProduct.setValueTempCountPackage((short)i);
	    }
	    if(UtilConverter.converterStringToShort(request,"_bonus") != -1)
	    	pharmacyProduct.setValueBonus(UtilConverter.converterStringToShort(request,"_bonus"));
    	pharmacyProduct.setValueDiscount(UtilConverter.converterStringToDouble(request,"_discount"));
    	pharmacyProduct.setValueTempStockId(UtilConverter.converterStringToShort(request,"_stock"));
	    if(UtilConverter.converterStringToInteger(request,"_requiresPrescription") == 1){	// requiresPrescription - >   1: true , 0:false
	    	pharmacyProduct.setRequiresPrescription(true);
	    	pharmacyProduct.setHaveExpirationDate(true);
	    }else{
	    	pharmacyProduct.setRequiresPrescription(false);
	    	pharmacyProduct.setHaveExpirationDate(false);
	    }
	    if(result.hasErrors())
	    	msg=" verifique los datos";
	    else{
	    	double cost = 0.0;
	    	if(purchaseUnit == 1)
	    		cost = (double)(UtilConverter.converterStringToDouble(request,"_costByPackage"));
	    	else
	    		cost = (double)(UtilConverter.converterStringToDouble(request,"_costByUnit"));
	    	
	    	if(pharmacyProductTemp == null){
	    		pharmacyProduct.setCost(cost);
	    		buyProductsTransactionService.addPharmacyProduct(pharmacyProduct);
	    		if(purchaseUnit == 1)
	    			addPackagesAndItems(pharmacyProduct,pharmacyProduct,cost,i,request);
	    		else
	    			addOnlyPackageAndItems(pharmacyProduct, pharmacyProduct, cost, i, request);
	    		msg=" Se Agrego ";
	    	}else{
	    		pharmacyProductTemp.setSurplusLevel(pharmacyProduct.getSurplusLevel());
	    		pharmacyProductTemp.setRepositionLevel(pharmacyProduct.getRepositionLevel());
	    		pharmacyProductTemp.setLocation(pharmacyProduct.getLocation());
	    		pharmacyProductTemp.setRequiresPrescription(pharmacyProduct.getRequiresPrescription());
	    		pharmacyProductTemp.setHaveExpirationDate(pharmacyProduct.getHaveExpirationDate());
	    		pharmacyProductTemp.setCost(cost);
	    		pharmacyProductTemp.setPackage1(pharmacyProduct.getPackage1());
	    		
	    		pharmacyProductTemp.setValueTempCountItem(pharmacyProduct.getValueTempCountItem());
	    		pharmacyProductTemp.setValueTempCountPackage(pharmacyProduct.getValueTempCountPackage());
	    		if(UtilConverter.converterStringToShort(request,"_bonus") != -1)
	    			pharmacyProductTemp.setValueBonus(pharmacyProduct.getValueBonus());
	    		pharmacyProductTemp.setValueDiscount(pharmacyProduct.getValueDiscount());
	    		pharmacyProductTemp.setValueTempStockId(pharmacyProduct.getValueTempStockId());
	    		buyProductsTransactionService.updatePharmacyProduct(pharmacyProductTemp);  
	    		if(purchaseUnit == 1)
	    			addPackagesAndItems(pharmacyProduct,pharmacyProductTemp,cost,i,request);
	    		else
	    			addOnlyPackageAndItems(pharmacyProduct, pharmacyProductTemp, cost, i, request);
	    		msg=" Se Modifico ";
	    	}
	    }
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("msg",msg);
		map.put("listPharmacyStock",getListPharmacyStockTemp(stockService.getListPharmacyStockByPharmacyIdByProviderId(s_pharmacyId,UtilConverter.converterStringToInteger(request,"providerId_"))));
		/*
		System.out.println(request.getParameterMap());
		
		Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String parameterName = (String) enumeration.nextElement();
            System.out.println(parameterName);
            System.out.println(request.getParameter(parameterName));
        }
        */
		return map;
    }
	private void addValuesRetailWholesale(Package packageElement,HttpServletRequest request){
		if(request.getParameter("checkbox_1") != null){
			int k = UtilConverter.converterStringToInteger(request,"_fare1");
			if(k == 0){
				if(UtilConverter.converterStringToDouble(request,"_amountFixed1") != -1.0)
					packageElement.setAmountFixe1(UtilConverter.converterStringToDouble(request,"_amountFixed1"));
				if(UtilConverter.converterStringToDouble(request,"_percentage1") != -1.0)
					packageElement.setPercentage1(UtilConverter.converterStringToDouble(request,"_percentage1"));
				packageElement.setUniquePrice1(false);
				packageElement.setTempUniquePrice1(true);
			}
			if(k == 1){
				if(UtilConverter.converterStringToDouble(request,"_amountFixed1") != -1.0)
					packageElement.setAmountFixe1(UtilConverter.converterStringToDouble(request,"_amountFixed1"));
				if(UtilConverter.converterStringToDouble(request,"_percentage1") != -1.0)
					packageElement.setPercentage1(UtilConverter.converterStringToDouble(request,"_percentage1"));
				packageElement.setUniquePrice1(true);
				packageElement.setTempUniquePrice1(true);
			}
			if(UtilConverter.converterStringToDouble(request,"_fareTotal1") != -1.0)
				packageElement.setTempTotal1(UtilConverter.converterStringToDouble(request,"_fareTotal1"));
		}
		if(request.getParameter("checkbox_2") != null){
			int k = UtilConverter.converterStringToInteger(request,"_fare2");
			if(k == 0){
				if(UtilConverter.converterStringToDouble(request,"_amountFixed2") != -1.0)
					packageElement.setAmountFixe2(UtilConverter.converterStringToDouble(request,"_amountFixed2"));
				if(UtilConverter.converterStringToDouble(request,"_percentage2") != -1.0)
					packageElement.setPercentage2(UtilConverter.converterStringToDouble(request,"_percentage2"));
				packageElement.setUniquePrice2(false);
				packageElement.setTempUniquePrice2(true);
			}
			if(k == 1){
				if(UtilConverter.converterStringToDouble(request,"_amountFixed2") != -1.0)
					packageElement.setAmountFixe2(UtilConverter.converterStringToDouble(request,"_amountFixed2"));
				if(UtilConverter.converterStringToDouble(request,"_percentage2") != -1.0)
					packageElement.setPercentage2(UtilConverter.converterStringToDouble(request,"_percentage2"));
				packageElement.setUniquePrice2(true);
				packageElement.setTempUniquePrice2(true);
			}
			if(UtilConverter.converterStringToDouble(request,"_fareTotal2") != -1.0)
				packageElement.setTempTotal2(UtilConverter.converterStringToDouble(request,"_fareTotal2"));
		}
	}
	private void addOnlyPackageAndItems(Pharmacyproduct pharmacyProduct,Pharmacyproduct pharmacyProductTemp,double cost,int i,HttpServletRequest request){
		double quantityOfItemTem = i*(UtilConverter.converterStringToDouble(request,"_quantityOfUnits"));
		while (i > 0) {
			Package packageElement = new Package(null,pharmacyProduct.getPackage1(),new Date(),UtilConverter.converterStringToDate(request,"_dueDate"));
			packageElement.setActive(true);
			packageElement.setPharmacyproduct(pharmacyProductTemp);
			packageElement.setUnitCost(cost/UtilConverter.converterStringToDouble(request,"_quantityOfUnits"));	
			packageElement.setBatchNumber(UtilConverter.converterStringToInteger(request,"_batchNumber"));	
			packageElement.setCost(cost);
			packageElement.setState((short)1);
			
			this.addValuesRetailWholesale(packageElement,request);
			buyProductsTransactionService.addPackage(packageElement);	    			
			int j = UtilConverter.converterStringToInteger(request,"_quantityOfUnits");
			while (j > 0) {
				Item item = new Item(packageElement.getPackageId(),j);
				item.setCost(UtilConverter.converterStringToDouble(request,"_priceTotalDcto")/quantityOfItemTem);
				item.setStockId(stockService.searchStockByStockId(UtilConverter.converterStringToInteger(request,"_stock")));
				item.setState((short)1);
				buyProductsTransactionService.addItem(item);
				j--;
			}
			i--;
		}
	}	
	private void addPackagesAndItems(Pharmacyproduct pharmacyProduct,Pharmacyproduct pharmacyProductTemp,double cost,int i,HttpServletRequest request){
		double quantityOfItemTem = UtilConverter.converterStringToDouble(request,"_quantityOfPackage")*(UtilConverter.converterStringToDouble(request,"_unitsByPackage"));
		while (i > 0) {
			Package packageElement = new Package(null,pharmacyProduct.getPackage1(),new Date(),UtilConverter.converterStringToDate(request,"_dueDate"));
			packageElement.setActive(true);
			packageElement.setPharmacyproduct(pharmacyProductTemp);
			packageElement.setUnitsPerPack(UtilConverter.converterStringToShort(request,"_unitsByPackage"));
			packageElement.setUnitCost(cost/UtilConverter.converterStringToDouble(request,"_unitsByPackage"));	
			packageElement.setBatchNumber(UtilConverter.converterStringToInteger(request,"_batchNumber"));
			packageElement.setCost(cost);
			packageElement.setState((short)1);

			this.addValuesRetailWholesale(packageElement,request);
			buyProductsTransactionService.addPackage(packageElement);	    			
			int j = UtilConverter.converterStringToInteger(request,"_unitsByPackage");
			while (j > 0) {
				Item item = new Item(packageElement.getPackageId(),j);
				item.setCost(UtilConverter.converterStringToDouble(request,"_priceTotalDcto")/quantityOfItemTem);
				item.setStockId(stockService.searchStockByStockId(UtilConverter.converterStringToInteger(request,"_stock")));
				item.setState((short)1);
				buyProductsTransactionService.addItem(item);
				j--;
			}
			i--;
		}
	}
	private ArrayList<Product> getListProductTemp(List<Product> listProductTemp){
		ArrayList<Product> listProduct = new ArrayList<Product>();
		for (Product product : listProductTemp) {
			Product p = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
			p.setName(product.getName());
			p.setPresentation(product.getPresentation());
			p.setActive(product.getActive());
			p.setGenericName(product.getGenericName());
			Activesubstance as = new Activesubstance(product.getActiveSubstanceId().getActiveSubstanceId(),product.getActiveSubstanceId().getSynonyms(),product.getActiveSubstanceId().getName(),product.getActiveSubstanceId().getTherapeuticAction(),product.getActiveSubstanceId().getProperties());
			p.setActiveSubstanceId(as);
			p.setCode(product.getCode());
			p.setCodeBar(product.getCodeBar());
			
			if(product.getPharmacyProduct() != null){
			Pharmacyproduct pp = new Pharmacyproduct(product.getPharmacyProduct().getPharmacyproductPK().getPharmacyId(),product.getPharmacyProduct().getPharmacyproductPK().getProviderId(),product.getPharmacyProduct().getPharmacyproductPK().getProductId()); 
			pp.setRepositionLevel(product.getPharmacyProduct().getRepositionLevel());
			pp.setPackage1(product.getPharmacyProduct().getPackage1());
			pp.setService(product.getPharmacyProduct().getService());
			pp.setRequiresPrescription(product.getPharmacyProduct().getRequiresPrescription());
			pp.setLocation(product.getPharmacyProduct().getLocation());
			pp.setActive(product.getPharmacyProduct().getActive());
			p.setPharmacyProduct(pp);
			}
			List<Composition> listCompositionTemp = (List<Composition>)product.getCompositionCollection();
			List<Composition> listComposition = new ArrayList<Composition>();
			for (Composition c : listCompositionTemp) {
				Composition composition = new Composition(c.getCompositionId(),c.getName(),c.getQuantity(),c.getActive());
				Typecomposition typeComposition = new Typecomposition(c.getTypeCompositionId().getTypeCompositionId(),c.getTypeCompositionId().getName());
				composition.setTypeCompositionId(typeComposition);
				Product p1 = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
				p1.setName(product.getName());
				p1.setPresentation(product.getPresentation());
				p1.setActive(product.getActive());
				p1.setGenericName(product.getGenericName());
				composition.setProduct(p1);
				listComposition.add(composition);
			}
			List<Productattributes> listProductAttributesTemp = (List<Productattributes>)product.getProductattributesCollection();
			List<Productattributes> listProductAttributes = new ArrayList<Productattributes>();
			for (Productattributes pa : listProductAttributesTemp) {
				Productattributes productAttributes = new Productattributes(pa.getProductattributesPK().getProductAttributeId(),pa.getProductattributesPK().getProviderId(),pa.getProductattributesPK().getProductId()); 
				listProductAttributes.add(productAttributes);
			}
			p.setCompositionCollection(listComposition);
			p.setProductattributesCollection(listProductAttributes);
			listProduct.add(p);
		}
		return listProduct;
	}
	private ArrayList<Pharmacystock> getListPharmacyStockTemp(List<Pharmacystock> listPharmacyStockTemp){
	    ArrayList<Pharmacystock> listPharmacyStock = new ArrayList<Pharmacystock>();
	    for (Pharmacystock pharmacystock : listPharmacyStockTemp) {
	    	Pharmacystock ps = new Pharmacystock(pharmacystock.getPharmacystockPK().getPharmacyId(),pharmacystock.getPharmacystockPK().getStockId());
	    	listPharmacyStock.add(ps);
		}	    
	    List<Stock> listStock = new ArrayList<Stock>();
	    for (Pharmacystock pharmacystock : listPharmacyStockTemp) {
	    	Stock s = new Stock(pharmacystock.getPharmacystockPK().getStockId(), pharmacystock.getStock().getName());
	    	List<Item> listItem= (List<Item>)pharmacystock.getStock().getItemCollection();
	    	ArrayList<Item> listItemAux = new ArrayList<Item>();
	    	for (Item item : listItem) {
				Item itemAux = new Item(item.getItemPK().getPackageId(),item.getItemPK().getItemId());
				itemAux.setCost(item.getCost());
				itemAux.setState(item.getState());
				itemAux.setStockId(new Stock(pharmacystock.getPharmacystockPK().getStockId(), pharmacystock.getStock().getName()));
				Package  packageTemp = new Package(item.getPackage1().getPackageId(),item.getPackage1().getPackage1(),item.getPackage1().getDateIncome(),item.getPackage1().getDueDate());
				Pharmacyproduct pharmacyProductTemp = new Pharmacyproduct(item.getPackage1().getPharmacyproduct().getPharmacyproductPK().getPharmacyId(),item.getPackage1().getPharmacyproduct().getPharmacyproductPK().getProviderId(),item.getPackage1().getPharmacyproduct().getPharmacyproductPK().getProductId());
				pharmacyProductTemp.setRepositionLevel(item.getPackage1().getPharmacyproduct().getRepositionLevel());
				pharmacyProductTemp.setPackage1(item.getPackage1().getPharmacyproduct().getPackage1());
				pharmacyProductTemp.setService(item.getPackage1().getPharmacyproduct().getService());
				pharmacyProductTemp.setRequiresPrescription(item.getPackage1().getPharmacyproduct().getRequiresPrescription());
				pharmacyProductTemp.setHaveExpirationDate(item.getPackage1().getPharmacyproduct().getHaveExpirationDate());
				pharmacyProductTemp.setActive(item.getPackage1().getPharmacyproduct().getActive());
				packageTemp.setPharmacyproduct(pharmacyProductTemp);
				packageTemp.setState(item.getPackage1().getState());
				itemAux.setPackage1(packageTemp);
				listItemAux.add(itemAux);
			}
	    	s.setItemCollection(listItemAux);
	    	listStock.add(s);	   
		}
	    for (Stock stock : listStock) {
	    	ArrayList<Pharmacystock> list= new ArrayList<Pharmacystock>();
	    	for (Pharmacystock pharmacystock : listPharmacyStockTemp) {
				if(pharmacystock.getPharmacystockPK().getStockId() == stock.getStockId()){
					Pharmacystock ps = new Pharmacystock(pharmacystock.getPharmacystockPK().getPharmacyId(),pharmacystock.getPharmacystockPK().getStockId());
					list.add(ps);
				}
			}
	    	stock.setPharmacystockCollection(list);
		}	    
	    for (Pharmacystock pharmacystock : listPharmacyStock) {
	    	for (Stock stock : listStock) {
				if(stock.getStockId() == pharmacystock.getPharmacystockPK().getStockId()){
					pharmacystock.setStock(stock);
				}
			}
		}
		return listPharmacyStock;
	}
	
	
	
	
	@RequestMapping(value="/formNewVisitor", method=RequestMethod.GET)
	public String handleRequestFormNewVisitor(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			model.addAttribute("userProvider",new Userprovider());
			return UtilCommon.fReferenceAdd+"formVisitor";
		}else
			return redirectTransactionBuyProducts(request);
	}	
	@RequestMapping(value = "/formNewVisitor", method = RequestMethod.POST)
   	public @ResponseBody Map<String, Object> onSubmitFormNewVisitor(Userprovider userProvider,HttpServletRequest request){
		System.out.println(request.getParameterMap());
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("userProviderId",5);
		map.put("visitors",15);
		return map;
    }
}
